package logic

import (
	"context"
	"errors"
	"zero-cloud-disk/api/internal/svc"
	"zero-cloud-disk/api/internal/types"
	"zero-cloud-disk/api/models"
	"zero-cloud-disk/service/redis"
	"zero-cloud-disk/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type MailCodeSendLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMailCodeSendLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MailCodeSendLogic {
	return &MailCodeSendLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MailCodeSendLogic) MailCodeSend(req *types.MailCodeSendReq) (resp string, err error) {
	if req.Email == "" {
		return "", errors.New("邮箱格式错误")
	}
	// 查看邮箱是否注册
	count, err := l.svcCtx.Engine.Where("email = ?", req.Email).Count(new(models.UserBasic))
	if err != nil {
		return "", err
	}
	if count > 0 {
		return "", errors.New("邮箱已存在")
	}
	// 获取验证码, 发送
	rand := utils.RandNumber()
	err = utils.NewCode().Send(req.Email, "您的验证码为: "+rand)
	if err != nil {
		return "", err
	}
	// 存储 redis
	err = redis.Set(req.Email, rand)
	if err != nil {
		return "", err
	}
	return "", nil
}
